const options = @options();
const JSONRPCClient = require("./library/jsonrpc-client.js");

if (options.rootURL) {
    
    var client = new JSONRPCClient(options);

    var buildProxy = function(name, context) {
        return new Proxy(function(){

            var args = Array.prototype.slice.call(arguments,0);

            return @.async(function(){
                client.call(context.join("@") + "." + name,args,this.test);
            });
        },{
            get: function(target,method) {
                if (!target[method]){
                    target[method] = buildProxy(method,context.concat([name]));
                }
                return target[method];
            }
        })
    }

    @lab.export.service(@kitty().name.split(".").join("_"), new Proxy({},{
        get: function(target,domain){
            if (!target[domain]){
                target[domain] = new Proxy({},{
                    get: function(subTarget,method){
                        if (["bind","length","name"].indexOf(method) < 0){
                            if (!subTarget[method]){
                                subTarget[method] = buildProxy(method,[domain]);
                            }
                            return subTarget[method];
                        } else {
                            return subTarget[method];
                        }
                        
                    }
                })
            }
            return target[domain];
        }
    }));

} else {
    @error("non url provided for jsonrpc kitty :  " + @kitty().name);
}